package com.xiaoyy.core.config.util;


import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * ehcache 缓存工具类
 *
 * cacheName在ehcache.xml中配置
 */
@Configuration
public class EhcacheUtil {

    private final CacheManager manager;

    @Autowired
    public EhcacheUtil(CacheManager manager) {
        this.manager = manager;
    }

    public void put(String cacheName, String key, Object value) {
        if(manager.getCache(cacheName)==null){
            manager.addCache(cacheName);
        }

        Cache cache = manager.getCache(cacheName);
        Element element = new Element(key, value);
        cache.put(element);
    }

    public Object get(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        if(cache==null){
            return null;
        }
        Element element = cache.get(key);
        return element == null ? null : element.getObjectValue();
    }


    public Element getE(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        if(cache==null){
            return null;
        }
        return cache.get(key);
    }
    public Cache get(String cacheName) {
        return manager.getCache(cacheName);
    }

    public void remove(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        if(cache!=null){
            cache.remove(key);
        }
    }
    public void remove(String cacheName) {
        Cache cache = manager.getCache(cacheName);
        if(cache!=null){
            cache.removeAll();
        }
    }

}  